<?php
namespace app\login\controller;

use think\Request;
use think\Session;

class Code
{
    public function sendcode(Request $request)
    {
	    $phone = $request->param("phone");
	    if ($phone == null || strlen($phone) != 11)
		return ;

	    \think\Log::write(sprintf("%s send code.", $phone));
	    $host = "http://sms.market.alicloudapi.com";
	    $path = "/singleSendSms";
	    $method = "GET";
	    $appcode = "c87b2c80d48449be8eb8e6cb207db61d";
	    $headers = array();
	    array_push($headers, "Authorization:APPCODE " . $appcode);
		$code = $this->GenCode();
		$querys = sprintf('ParamString={"no":"%d"}&RecNum=%s&SignName=%s&TemplateCode=%s', $code, $phone, "媒美", "SMS_109370339");
	    //$querys = "ParamString=%7B%22no%22%3A%22123456%22%7D&RecNum=RecNum&SignName=SignName&TemplateCode=TemplateCode";
	    $bodys = "";
	    $url = $host . $path . "?" . $querys;

	    $curl = curl_init();
	    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
	    curl_setopt($curl, CURLOPT_URL, $url);
	    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
	    curl_setopt($curl, CURLOPT_FAILONERROR, false);
	    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	    curl_setopt($curl, CURLOPT_HEADER, true);
	    if (1 == strpos("$".$host, "https://"))
	    {
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
	    }
		
		$result = curl_exec($curl);	
		$errorCode = curl_errno($curl);
		curl_close($curl);
		trace("$errorCode:" . $errorCode);
		if ($errorCode)
		{
			\think\Log::write(sprintf("%s send code error : %d", $phone, $errorCode));
			return json(["ErrorCode" => 1]);
		}
		else
		{
			preg_match("/{.*}/", $result, $matches);
			if (count($matches) == 0)
				return json(["ErrorCode" => 1]);
			else
			{
				$jsarray = json_decode($matches[0], true);
				trace($jsarray);
				if ($jsarray['success'])
				{
					session("phonecode", $code);
					session("phonecodetime", time());
	    				\think\Log::write(sprintf("%s send code success[code:%d].", $phone, $code));
					return json(["ErrorCode" => 0]);
				}
				else
				{
					\think\Log::write(sprintf("%s send code error : %s", $phone, $jsarray['message']));
					return json(["ErrorCode" => 1]);	
				}
			}
		}
    }
	
	private function GenCode()
	{
		 $r = mt_rand(100000, 999999);
		 return $r;
	}
} 
